package com.droidnova.android.games.vortex;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.util.AttributeSet;

public class MapView extends GLSurfaceView implements Renderer {

private int w, h;

private FloatBuffer frameVertices;

private ByteBuffer diagIndices;

public MapView(Context ctx) { this(ctx, null); }

public MapView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setRenderer(this);
}

@Override
public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, frameVertices);
    gl.glColor4f(0f, 0f, 1f, 0.5f);
    gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, 4);
    gl.glDrawElements(GL10.GL_LINES, 1, GL10.GL_UNSIGNED_BYTE, diagIndices);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    // TODO Auto-generated method stub

}

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    w = getWidth(); h =  getHeight();
    
    gl.glClearColor(0, 0, 0, 1);
    gl.glViewport(0, 0, w, h);
    gl.glDepthRangex(1, -1);    // TODO remove
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glOrthof(0, w, 0, h, 1, -1);

    float[] frame = {
        0, 0,
        w-1, 0,
        w-1, h-1,
        0, h-1 };
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(frame.length * 4);
    byteBuffer.order(ByteOrder.nativeOrder());
    frameVertices = byteBuffer.asFloatBuffer();
    frameVertices.put(frame);
    frameVertices.flip();
    frameVertices.position(0);
    gl.glLineWidthx(10);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();
    gl.glDisable(GL10.GL_DEPTH_TEST);
    diagIndices = ByteBuffer.allocateDirect(2);
    diagIndices.order(ByteOrder.nativeOrder());
    diagIndices.put(new byte[] {0, 2});
    diagIndices.flip();
}

}
